package com.youlu.campus.service.ranking.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.*;
import com.youlu.campus.service.organizer.ActivityOrganizerInfoService;
import com.youlu.campus.service.ranking.OrganizerRankingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class OrganizerRankingServiceImpl implements OrganizerRankingService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityOrganizerInfoService activityOrganizerInfoService;

    // 更新承办单位榜单
    @Override
    public void updateOrganizerRanking(final UserPO userPO, UserParticipateActivityTaskInfo taskInfo,
                                       final Integer optType) {
        log.info(":>>> 开始更新承办单位榜单用户:{},任务数据:{},操作类型:{}", JSON.toJSONString(userPO),
                JSON.toJSONString(taskInfo), optType);
        if (Objects.isNull(userPO) || Objects.isNull(taskInfo) || Objects.isNull(optType)) {
            log.error(":>>> 更新更新承办单位榜单参数错误:用户、任务量、操作类型为空");
            return;
        }
        ActivityOrganizerInfo organizerInfo = activityOrganizerInfoService.findOne(taskInfo.getOrganizerId());
        if (Objects.isNull(organizerInfo)) {
            log.error(":>>> 承办单位为空:{}", taskInfo.getOrganizerId());
            return;
        }
        Date date = new Date();
        Query query = new Query();
        query.addCriteria(Criteria.where("organizerId").is(taskInfo.getOrganizerId()).and("taskId").is(taskInfo.getTaskId()).and("activityId").is(taskInfo.getActivityId()));
        OrganizerRankingList ranking = mongoTemplate.findOne(query, OrganizerRankingList.class);
        if (Objects.isNull(ranking)) {
            ranking = new OrganizerRankingList();
            ranking.setActivityId(taskInfo.getActivityId());
            ranking.setUserId(userPO.getId());
            ranking.setTaskId(taskInfo.getTaskId());
            ranking.setTaskBizType(taskInfo.getBizType());
            ranking.setCreatedTime(date);
            ranking.setUniversityName(userPO.getUniversityName());
            ranking.setImageUrl(organizerInfo.getLogoImageUrl());
            ranking.setName(organizerInfo.getOrgName());
            ranking.setQuantity(taskInfo.getQuantity());
            ranking.setUniversityId(userPO.getUniversityId());
            ranking.setOrganizerId(taskInfo.getOrganizerId());
            if (StringUtils.isNotBlank(userPO.getUniversityId())) {

                Query queryU = new Query().addCriteria(Criteria.where("id").is(userPO.getUniversityId()));
                UniversityInfo universityInfo = mongoTemplate.findOne(queryU, UniversityInfo.class);
                if (Objects.nonNull(universityInfo)) {
                    ranking.setUniversityName(universityInfo.getName());
                }
            }
            mongoTemplate.insert(ranking);
            return;
        }
        Query queryUpdate = new Query().addCriteria(Criteria.where("id").is(ranking.getId()));
        Update update = new Update();
        switch (optType) {
            // 累加
            case 0:
                update.inc("quantity", taskInfo.getQuantity());
                break;
            // 替换
            case 1:
                update.set("quantity", taskInfo.getQuantity());
                break;
            default:
                break;
        }
        update.set("updatedTime", date);
        UpdateResult result = mongoTemplate.updateFirst(queryUpdate, update, OrganizerRankingList.class);
        log.info(":>>> 更新用户:{},任务榜单:{},结果数量为:{}", userPO.getId(), ranking.getId(), result.getModifiedCount());
    }

    @Override
    public Integer getOrgOrder(String activityId, String orgId) {
        log.info(":>>> 开始获取承办单位名次:{},{}", activityId, orgId);
        Long current = System.currentTimeMillis();
        if (Objects.isNull(orgId) || StringUtils.isBlank(orgId)) {
            return 0;
        }
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        List<OrganizerRankingList> ranks = mongoTemplate.find(query, OrganizerRankingList.class);
        if (CollectionUtils.isEmpty(ranks)) {
            return 0;
        }
        Integer counter = 0;
        for (OrganizerRankingList r : ranks) {
            if (orgId.equals(r.getOrganizerId())) {
                break;
            }
            counter++;
        }
        log.info(":>>> 结果获取承办单位名次:{} ,耗时:{} 毫秒", orgId, (System.currentTimeMillis() - current));
        return counter;
    }

    @Override
    public void updateOrganizerRankingStatus(String orgId, String activityId, Integer status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("organizerId").is(orgId).and("activityId").is(activityId));
        Update update = new Update();
        update.set("status", status);
        update.set("updatedTime", new Date());
        mongoTemplate.updateMulti(query, update, OrganizerRankingList.class);
    }
}
